package com.swu.cx.alwayslearning.util

import android.util.Log
import com.swu.cx.alwayslearning.AccountManager
import com.swu.cx.alwayslearning.retrofit.DownloadApi
import retrofit2.Retrofit
import java.io.*

object DownLoadUtil {

    suspend fun downloadDex(): String {
        val path = "${FileUtil.getRootPath()}/java29patch.dex"
        val retrofit = Retrofit.Builder()
                .baseUrl(AccountManager.MyHost)
                .build()
        val api = retrofit.create(DownloadApi::class.java)
        val response = api.downLoadDexFile().execute()
        if (response.isSuccessful && response.body() != null) {
            response.body()?.byteStream().use {
                it?.readBytes()
            }?.let { save(path, it) }
        } else {
            Log.e("cx","错误信息：${response.message()}")
        }
        return path
    }

    fun readContent(_is: FileInputStream): ByteArray {
        val byteRes = byteArrayOf()
        var bis: BufferedInputStream? = null
        try {
            bis = BufferedInputStream(_is)
            var len = 0
            while (len != -1) {
                len = bis.read(byteRes)
            }
        } catch (e: Exception) {
            e.printStackTrace()
        } finally {
            bis?.closeIO()
            _is.closeIO()
        }
        return byteRes
    }

    fun save(path: String, contents: ByteArray) {
        val file = createFile(path)
        var os: FileOutputStream? = null
        var bos: BufferedOutputStream? = null
        try {
            os = FileOutputStream(file)
            bos = BufferedOutputStream(os)
            bos.write(contents)
            bos.flush()
        } catch (e: Exception) {
            e.printStackTrace()
        } finally {
            bos?.closeIO()
            os?.closeIO()
        }
    }

    fun createFile(path: String): File {
        val file = File(path)
        if (!file.exists()) {
            file.createNewFile()
        }
        return file
    }

}